package samsung.sds.system.listener;

import java.util.List;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import samsung.sds.system.utils.CommonTools;
import samsung.sds.systemMonitor.userOperationMonitor.model.MonitorOperationEntity;
import samsung.sds.systemMonitor.userOperationMonitor.service.UserOperationMonitorService;
import samsung.sds.systemMonitor.userOperationMonitor.utils.Constants;

/**
 * 
 * 监听session的创建和销毁
 * 
 * @author lixin.qiu
 * @createDate 2016-02-25
 */
public class UserOperationSessionListener implements HttpSessionListener {

	@Override
	public void sessionCreated(HttpSessionEvent se) {

	}

	/**
	 * 销毁session对应的用户日志改为登出
	 */
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		HttpSession session = se.getSession();
		MonitorOperationEntity monitorOperationEntity = (MonitorOperationEntity) session
				.getServletContext().getAttribute(session.getId());
		if (monitorOperationEntity != null) {
			UserOperationMonitorService userOperationMonitorServiceImpl = (UserOperationMonitorService) session
					.getServletContext().getAttribute(
							"UserOperationMonitorService");
			monitorOperationEntity.setId(CommonTools.getKeyUUID());
			monitorOperationEntity.setOpType(Constants.SUCCESS_LOGOUT);
			monitorOperationEntity.setCreateTime(CommonTools
					.getCurrentDateTime());
			
			//清除用户绑定的session
			session.getServletContext().removeAttribute(
					monitorOperationEntity.getCreateUser());
			session.getServletContext().removeAttribute(session.getId());
			session.getServletContext().removeAttribute(
					"UserOperationMonitorService");
			
			//清除inlineUserNames里下线的用户
			@SuppressWarnings("unchecked")
			List<String> inlineUserNames = (List<String>) session
					.getServletContext().getAttribute("INLINE_USERNAMES");
			inlineUserNames.remove(monitorOperationEntity.getCreateUser());
			session.getServletContext().setAttribute("INLINE_USERNAMES",
					inlineUserNames);
			
			//插入登出日志
			userOperationMonitorServiceImpl
					.insertEntity(monitorOperationEntity);
		}

	}
}
